package com.yufubao.service.service.management.authorization.impl;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yufubao.framework.enums.CommonExceptionEnum;
import com.yufubao.framework.exception.BaseException;
import com.yufubao.framework.result.ResponseResult;
import com.yufubao.framework.util.CopyBean;
import com.yufubao.model.dto.management.authorization.ManagerInfoParam;
import com.yufubao.model.dto.management.authorization.ManagerLoginDto;
import com.yufubao.model.dto.management.authorization.ManagerRegisterDto;
import com.yufubao.model.pojo.management.authorization.ManagerEntity;
import com.yufubao.model.vo.management.authorization.AdminManagerInfoVo;
import com.yufubao.model.vo.management.authorization.ManagerLoginVo;
import com.yufubao.model.vo.management.authorization.RoutersVo;
import com.yufubao.service.service.management.authorization.ManagementPowerService;
import com.yufubao.service.service.management.authorization.ManagerService;
import com.yufubao.service.service.management.authorization.MenuService;
import com.yufubao.service.service.management.authorization.RoleService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

import static com.yufubao.framework.constant.AppletRedisKeysConstant.SMS_CODE;
import static com.yufubao.framework.constant.ManagerStatus.OPEN;
import static com.yufubao.framework.constant.ManagerStatus.STOP;
import static com.yufubao.framework.enums.CommonExceptionEnum.GLYZCCG;

/**
 * @author 张一恒
 * @version 1.0
 * @description:
 * @date 2024/9/2 20:07
 */
@Slf4j
@Service("managementPowerService")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ManagementPowerServiceImpl implements ManagementPowerService {

    private final StringRedisTemplate stringRedisTemplate;
    private final ManagerService managerService;
    private final MenuService menuService;
    private final RoleService roleService;
    private final HttpServletRequest request;

    /**
     * @param dto
     * @return com.yufubao.framework.result.ResponseResult
     * @description 注册
     * @author zhangyiheng
     * @date 2024/9/2 20:14
     */
    @Override
    @Transactional
    public ResponseResult enroll(ManagerRegisterDto dto) {

        //判断验证码
        String code = dto.getCode();
        String cacheCode = stringRedisTemplate.opsForValue().get(SMS_CODE + dto.getPhone());
        if (StrUtil.isBlank(cacheCode) || StrUtil.isBlank(cacheCode.split("_")[0])) {
            throw new BaseException(CommonExceptionEnum.DODE_ERROR);
        } else {
            cacheCode = cacheCode.split("_")[0];
            if (code.equals(cacheCode)) {
                //验证码正确
                stringRedisTemplate.delete(SMS_CODE + dto.getPhone());

                //判断账号是否存在，判断手机号是否以绑定过账号
                ManagerEntity manager = managerService.getOne(Wrappers.<ManagerEntity>lambdaQuery()
                        .eq(ManagerEntity::getAccount, dto.getAccount())
                        .or()
                        .eq(ManagerEntity::getPhone, dto.getPhone()));
                if (!Objects.isNull(manager)) {
                    if (manager.getAccount().equals(dto.getAccount())) {
                        throw new BaseException(CommonExceptionEnum.ZHYCZ);
                    } else {
                        throw new BaseException(CommonExceptionEnum.MPNAD);
                    }
                }

                //注册
                //密码加密
                BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
                dto.setPassword(bCryptPasswordEncoder.encode(dto.getPassword()));

                ManagerEntity managerEntity = CopyBean.copyBean(dto, ManagerEntity.class);
                managerEntity.setStatus(OPEN);
                managerService.save(managerEntity);
                log.info("管理员：{} 注册成功", dto.getAccount());

                return ResponseResult.ok(GLYZCCG);
            }
        }
        return null;
    }

    /**
     * @param dto
     * @return com.yufubao.framework.result.ResponseResult
     * @description 登录
     * @author zhangyiheng
     * @date 2024/9/2 20:55
     */
    @Override
    public ResponseResult login(ManagerLoginDto dto) {

        ManagerEntity manager = managerService.getOne(Wrappers.<ManagerEntity>lambdaQuery()
                .eq(ManagerEntity::getAccount, dto.getAccount())
                .or()
                .eq(ManagerEntity::getPhone, dto.getAccount()));

        if (Objects.isNull(manager)) {
            throw new BaseException(CommonExceptionEnum.DLSB_WCZHHYBSC);
        }

        //判断账号状态
        if (Objects.equals(manager.getStatus(), STOP)) {
            throw new BaseException(CommonExceptionEnum.DLSB_ZHYBJY);
        }

        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        if (!bCryptPasswordEncoder.matches(dto.getPassword(), manager.getPassword())) {
            throw new BaseException(CommonExceptionEnum.VALID_LOGIN_USER_EXCEPTION);
        }

        StpUtil.login(manager.getManagerId());
        // 用户登录后，将登录时间和ip记录到数据库
        manager.setLastTime(LocalDateTime.now());
        if (request != null) {
            manager.setLoggedIp(request.getRemoteAddr());
        }
        managerService.updateById(manager);

        //账号密码验证成功 构建返回信息
        StpUtil.getSession().set(SaSession.USER, manager);
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        ManagerLoginVo managerLoginVo = new ManagerLoginVo();
        managerLoginVo.setManager(manager);
        managerLoginVo.setTokenName(tokenInfo.getTokenName());
        managerLoginVo.setTokenValue(tokenInfo.getTokenValue());
        return ResponseResult.okResult(managerLoginVo);
    }


    /**
     * @return com.yufubao.framework.result.ResponseResult<com.yufubao.model.vo.bms.AdminManagerInfoVo>
     * @description 查询人员权限信息
     * @author zhangyiheng
     * @date 2024/9/4 15:54
     */
    @Override
    public ResponseResult<AdminManagerInfoVo> getInfo() {
        //获取当前登录的人员
        ManagerEntity manager = StpUtil.getSession().getModel(SaSession.USER, ManagerEntity.class);
        //根据人员id查询权限信息
        List<String> perms = menuService.selectPermsByManagerId(manager.getManagerId());
        //根据人员id查询角色信息
        List<String> roleKeyList = roleService.selectRoleKeyByManagerId(manager.getManagerId());

        //获取人员信息
        ManagerInfoParam managerInfoParam = CopyBean.copyBean(manager, ManagerInfoParam.class);
        //封装数据返回

        AdminManagerInfoVo adminManagerInfoVo = new AdminManagerInfoVo(perms, roleKeyList, managerInfoParam);
        return ResponseResult.okResult(adminManagerInfoVo);
    }


    /**
     * @return com.yufubao.framework.result.ResponseResult<com.yufubao.model.vo.bms.RoutersVo>
     * @description 查询人员菜单路由路径
     * @author zhangyiheng
     * @date 2024/9/4 16:38
     */
    @Override
    public ResponseResult<RoutersVo> getRouters() {
        ManagerEntity manager = StpUtil.getSession().getModel(SaSession.USER, ManagerEntity.class);
        //查询menu 结果是tree的形式
        RoutersVo menus = menuService.selectRouterMenuTreeByManagerId(manager);
        //封装数据返回
        return ResponseResult.okResult(menus);
    }
}
